<template>
  <div class="relative fee-pane-content">
    <page-form :model="feeForm" ref="formRef" layout="vertical">
      <template v-for="(item, index) in feeForm.orderFee" :key="index">
        <div class="order-fee-item">
          <div class="order-fee-item-header">
            <div class="line"></div>
            <div class="text"> {{ orderInfo.feeName }}</div>
          </div>
          <div class="order-fee-item-content">
            <fee-pane :orderFeeIndex="index" @feeChange="feeChangeFn">
              <template #feePaneHeader="{ feeTypeDisabled, feeTypeOptionList }">
                <ve-form-item class="order-fee-item-name" :borderBottom="false" :label="orderInfo.feeName">
                  <ve-radio v-model="item.feeType" :disabled="feeTypeDisabled" :list="feeTypeOptionList" />
                </ve-form-item>
              </template>
              <template #returnDepositFee="{ feeOption, showDivider }">
                <ve-card :title="feeOption.feeName" :showDivider="showDivider">
                  <edit-return-deposit :orderId="orderInfo.orderId" />
                </ve-card>
              </template>
            </fee-pane>
          </div>
        </div>
      </template>
      <!-- 账单分期计划 -->
      <div class="pd" v-if="isShowPayment">
        <order-payment-pane :contractAmount="feeRealtimeSum" />
      </div>
    </page-form>
  </div>
</template>
<script setup>
  import { ref, computed, provide } from 'vue'
  import dayjs from 'dayjs'
  import { isValid } from '@/utils'
  import { czsOrderFeeDetailAPI, modifyOrderFee, calcRateAPI } from '@/api/order/czsOrder'
  import feePane from '../order-fee/fee-pane.vue'
  import orderPaymentPane from '../order-payment-pane.vue'
  import { getFeeSum } from '../order-fee/fee-statistic'
  import { buildCostInfoParam, initFeeDetail, handleStoreTemplateDetail } from '../order-fee/fee-utils.js'
  import editReturnDeposit from '../return-car/edit-return-deposit.vue'

  const props = defineProps({
    id: [Number, String],
  })

  // formRef
  const formRef = ref()
  const feeId = +props.id
  const orderFeeId = ref()
  orderFeeId.value = feeId
  const feeForm = ref({})
  provide('feeForm', feeForm)
  provide('form', feeForm)

  // 实时费用信息开始
  const feeRealtimeSum = computed(() => {
    let orderFee = feeForm.value.orderFee
    if (orderFee) {
      return getFeeSum(orderFee)
    }
    return 0
  })
  // 费用类型汇总
  // INIT(1, "租车费", true),
  // RERENT(2, "续租", true),
  // ADDITIONAL(3, "额外费用", true),
  // OTHER(4, "其他费用", true),
  // REFUND(5, "退款", true),
  // GIVE_CAR(6, "交车费", true),
  // RETURN_CAR(7, "还车费", true),
  // SERVICE_AMOUNT(8, "增值服务费", true),
  // REPLACE_CAR(9, "换车费", true),
  // CANCEL(10, "取消订单", true),
  // DISCOUNT(11, "优惠费", true),
  // CAR_DEPOSIT(12, "租车押金", false),
  // ILLEGAL_DEPOSIT(13, "违章押金", false),
  // BACK_CAR_DEPOSIT(14, "退租车押金", false),
  // BACK_ILLEGAL_DEPOSIT(15, "退违章押金", false),
  const orderInfo = ref({})
  const reletMonths = ref(0)
  provide('orderInfo', orderInfo)
  czsOrderFeeDetailAPI({ id: feeId }).then(({ result }) => {
    const info = result.czsOrderFeeList[0]
    orderInfo.value = info
    const feeNameId = info.feeNameId
    let feeDetailTypeList = []
    reletMonths.value = result.months
    // 租车费
    switch (feeNameId) {
      case 1:
        feeDetailTypeList = ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee']
        break
      case 2:
        feeDetailTypeList = ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee']
        break
      case 3:
        feeDetailTypeList = ['extraFee']
        break
      case 4:
        feeDetailTypeList = ['otherFee']
        break
      case 5:
        feeDetailTypeList = ['refuseFee']
        break
      case 6:
        feeDetailTypeList = ['addServiceFee', 'preferentialFee', 'otherFee']
        break
      case 7:
        feeDetailTypeList = ['extraFee', 'returnRefuseFee', 'returnDepositFee']
        break
      case 8:
        feeDetailTypeList = ['addServiceFee']
        break
      case 9:
        feeDetailTypeList = ['extraFee']
        break
      case 10:
        feeDetailTypeList = ['cancelOrder']
        break
      case 11:
        feeDetailTypeList = ['preferentialFee']
        break
      case 12:
        feeDetailTypeList = ['depositCarRentalFee']
        break
      case 13:
        feeDetailTypeList = ['depositViolationFee']
        break
      case 14:
        feeDetailTypeList = ['returnDepositCarRentalFee']
        break
      case 15:
        feeDetailTypeList = ['returnDepositViolationFee']
        break
    }
    // 创建费用时的费用模板快照
    let priceTemplateSnapshot = info.priceTemplateSnapshot
    // 解析后的费用模板
    let storeTemplate = null
    if (priceTemplateSnapshot) {
      priceTemplateSnapshot = JSON.parse(priceTemplateSnapshot)
      storeTemplate = handleStoreTemplateDetail(priceTemplateSnapshot)
    }
    feeForm.value = {
      id: feeId,
      feeNameId: info.feeNameId,
      costType: info.costType,
      feeType: info.feeType,
      feeStatus: info.feeStatus,
      depositDeductFlag: isValid(info.depositDeductionAmount) ? 1 : 0,
      changeDepositFlag: 0,
      orderFee: [
        {
          // 费用类型（线上费用|线下费用）
          feeType: info.feeType,
          feeDetailList: [],
          feeDetailTypeList,
        },
      ],
    }
    // 处理分期信息
    // 处理租车费或者续租费
    if (feeNameId == 1 || feeNameId == 2) {
      feeForm.value.paymentScheme = 1
      // 默认分期方式
      feeForm.value.paymentMethod = 2
      // 首期付款日默认值
      feeForm.value.lnstalmentFirstDate = dayjs().format('YYYY-MM-DD HH:mm:ss')

      // 获取当前订单的租期和时间
      getRate()
    }
    let feeValue = feeForm.value
    initFeeDetail(feeValue, storeTemplate)
    // 回显
    // 默认费用
    let feeDetailList = info.feeDetailList
    let formfeeDetailList = feeForm.value.orderFee[0].feeDetailList
    formfeeDetailList.forEach((formFeeDetailItem) => {
      let findResult = feeDetailList?.find((item) => {
        let sameFeeCategory = item.feeCategory == formFeeDetailItem.feeCategory
        let sameFeeName = item.itemName == formFeeDetailItem.feeName
        return sameFeeCategory || sameFeeName
      })
      if (findResult) {
        formFeeDetailItem.categoryType = findResult.type
        formFeeDetailItem.id = findResult.id
        formFeeDetailItem.compensateReason = findResult.compensateReason
        if (findResult.type == 1) {
          formFeeDetailItem.remark = info.remark
        } else {
          formFeeDetailItem.remark = findResult.remark
        }
      } else {
        formFeeDetailItem.categoryType = 0
        if (![1, 2, 6, 7].includes(orderInfo.value.feeNameId)) {
          formFeeDetailItem.remark = info.remark
        }
      }
      formFeeDetailItem.childrenList?.forEach((item) => {
        let findFeeDetail = findResult?.childrenList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
        if (!findFeeDetail) {
          findFeeDetail = feeDetailList?.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
        }
        if (findFeeDetail && findFeeDetail.itemName == '押金抵扣') {
          findFeeDetail = null
        }
        if (findFeeDetail) {
          // 处理日租价
          if (item.itemName == '车辆租金') {
            let unitPrice = findFeeDetail.unitPrice
            let findResult3 = formFeeDetailItem.childrenList.find((item2) => item2.itemName == '月租价（标准）')
            findResult3 && (findResult3.amount = unitPrice)
          }
          if (item.itemName == '手续费') {
            let unitPrice = findFeeDetail.unitPrice
            let findResult3 = formFeeDetailItem.childrenList.find((item2) => item2.itemName == '手续费（标准）')
            findResult3 && (findResult3.amount = unitPrice)
          }
          if (item.itemName == '基础保险') {
            let unitPrice = findFeeDetail.unitPrice
            let findResult3 = formFeeDetailItem.childrenList.find((item2) => item2.itemName == '基础保险（标准）')
            findResult3 && (findResult3.amount = unitPrice)
          }
          item.amount = findFeeDetail.amount
          item.id = findFeeDetail.id
          item.statics = true
          item.costType = findFeeDetail.costType
        }
      })
    })
  })
  // 账单分期计划展示
  const isShowPayment = computed(() => {
    let feeNameId = orderInfo.value.feeNameId
    if ([1, 2].includes(feeNameId)) {
      if (feeNameId == 1) {
        return feeRealtimeSum.value > 0
      }
      // 续租时判断续租周期大于1个月
      if (feeNameId == 2) {
        return feeRealtimeSum.value > 0 && reletMonths.value > 0
      }
    }
    return false
  })
  const calcRate = ref()
  const getRate = (cb) => {
    if (calcRate.value) {
      cb && cb(calcRate.value)
    } else {
      const param = {
        id: orderFeeId.value,
      }
      calcRateAPI(param).then((res) => {
        const rate = res.result.rate
        calcRate.value = rate
        const rentDays = res.result.rentDays
        feeForm.value.leaseNumberStr = rentDays
        feeForm.value.rentDays = rentDays
        cb && cb(calcRate.value)
      })
    }
  }
  // 费用变化
  const feeChangeFn = (item, val, index) => {
    let feeDetailList = feeForm.value.orderFee[0].feeDetailList
    let option = feeDetailList[index].childrenList
    let itemName = item.itemName
    if (itemName == '月租价（标准）') {
      getRate((rate) => {
        let target = option.find((item) => item.itemName == '车辆租金')
        if (target) target.amount = val * rate
      })
    }
    if (itemName == '手续费（标准）') {
      let target = option.find((item) => item.itemName == '手续费')
      if (target) target.amount = val * 1
    }
    if (itemName == '基础保险（标准）') {
      getRate((rate) => {
        let target = option.find((item) => item.itemName == '基础保险')
        if (target) target.amount = val * rate
      })
    }
  }

  // 处理数据
  const handleOption = (option) => {
    let feeDetailList = []
    // 处理 remark
    if (![1, 2, 6, 7].includes(orderInfo.value.feeNameId)) {
      let remark
      for (let i = 0; i < option.feeDetailList.length; i++) {
        let item = option.feeDetailList[i]
        remark = item.remark
      }
      option.remark = remark
    }
    for (let i = 0; i < option.feeDetailList.length; i++) {
      let item = option.feeDetailList[i]
      if (item.type == 1) {
        let childrenList = item.childrenList
        if (childrenList?.length > 0) {
          for (let j = childrenList?.length - 1; j >= 0; j--) {
            let fee_item = {
              ...childrenList[j],
              type: 1,
              feeCategory: item.feeCategory,
            }
            option.feeDetailList.splice(i + 1, 0, fee_item)
          }
          option.feeDetailList.splice(i, 1)
          i--
        }
      }
    }
    option.feeDetailList.forEach((item) => {
      if (item.type == 1) {
        let originFeeDetailList = orderInfo.value.feeDetailList
        let orignItem = originFeeDetailList?.find((originItem) => originItem.itemName == item.itemName)
        feeDetailList.push({
          ...item,
          id: orignItem ? orignItem.id : undefined,
        })
      } else {
        feeDetailList.push(item)
      }
    })
    option.feeDetailList = feeDetailList
    return option
  }
  const submitFn = () => {
    return new Promise((resolve) => {
      formRef.value.validate((errors) => {
        // 有错误
        if (errors) {
          resolve(0)
        } else {
          let feeFormValue = feeForm.value
          let { orderFee } = buildCostInfoParam(feeFormValue)
          // 处理 option
          let option = handleOption(orderFee[0])
          const feeOption = {
            ...option,
            id: feeFormValue.id,
            feeNameId: feeFormValue.feeNameId,
            costType: feeFormValue.costType,
            feeStatus: feeFormValue.feeStatus,
          }
          // 处理分期信息
          if (orderInfo.value.feeNameId == 1 || orderInfo.value.feeNameId == 2) {
            feeOption.paymentScheme = feeFormValue.paymentScheme
            if (feeOption.paymentScheme == 2) {
              feeOption.paymentMethod = feeFormValue.paymentMethod
              feeOption.lnstalmentFirstDate = feeFormValue.lnstalmentFirstDate
            }
          }
          // 编辑还车费
          if (orderInfo.value.feeNameId == 7) {
            feeOption.depositDeductFlag = feeFormValue.depositDeductFlag
            feeOption.depositDeductAmount = feeFormValue.depositDeductAmount
            feeOption.changeDepositFlag = feeFormValue.changeDepositFlag
            feeOption.changeDepositAmount = feeFormValue.changeDepositAmount
          }
          delete feeOption.priceTemplateId
          const param = {
            id: feeFormValue.id,
            czsOrderFeeList: [feeOption],
          }
          modifyOrderFee(param).then((res) => {
            resolve(res.code)
          })
        }
      })
    })
  }

  defineExpose({
    submitFn,
  })
</script>
<style lang="less" scoped>
  :deep(.arco-card) {
    background-color: inherit;
  }
  .order-fee-item {
    border-radius: 2px;
    padding: 16px;
    margin-bottom: 20px;
    .order-fee-item-header {
      margin-bottom: 8px;
      font-size: 14px;
      color: #1d2129;
      line-height: 22px;
      display: flex;
      align-items: center;
      .line {
        width: 3px;
        height: 16px;
        display: inline-block;
        background: #1890ff;
        margin-right: 8px;
      }
      .text {
        font-size: 16px;
        font-weight: 500;
        color: #1d2129;
        line-height: 22px;
      }
    }
  }
  .pd {
    padding: 0 20px;
  }
</style>
